package com.moive.news.tqnewsapplication.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.event.SenEvent;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.photo.PhotoPickerActivity;
import com.moive.news.tqnewsapplication.photo.utils.LogUtils;
import com.moive.news.tqnewsapplication.runtimepermissions.PermissionsManager;
import com.moive.news.tqnewsapplication.runtimepermissions.PermissionsResultAction;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.TimeUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.ClearEditText;
import com.upyun.library.common.Params;
import com.upyun.library.common.UploadEngine;
import com.upyun.library.listener.UpCompleteListener;
import com.upyun.library.listener.UpProgressListener;
import com.upyun.library.utils.UpYunUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

import static com.moive.news.tqnewsapplication.networks.BaseApi.BASEUR_IMG;
import static com.moive.news.tqnewsapplication.networks.BaseApi.PASSWORD;

/**
 * Created by Administrator on 2017/12/12.
 */

public class PersonActivity extends BaseActivity {
    @BindView(R.id.peron_back)
    ImageView peronBack;
    @BindView(R.id.person_img_realte)
    RelativeLayout personImgRealte;
    @BindView(R.id.persion_nichen)
    TextView persionNichen;
    @BindView(R.id.person_nichen_realte)
    RelativeLayout personNichenRealte;
    @BindView(R.id.persion_sex)
    TextView persionSex;
    @BindView(R.id.person_sex_realte)
    RelativeLayout personSexRealte;
    @BindView(R.id.persion_phone)
    TextView persionPhone;
    @BindView(R.id.person_phone_realte)
    RelativeLayout personPhoneRealte;
    @BindView(R.id.peron_button)
    Button peronButton;
    @BindView(R.id.persion_img)
    CircleImageView persionImg;

    private String nichen = "", userimgurl = "";
    private int sex = -1;
    private String[] sexArry = new String[]{"女", "男"};// 性别选择

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        peronBack.setOnClickListener(v -> finish());
        String img = PreferenceUtil.getString("headImg", "");
        Glide.with(PersonActivity.this)
                .load(img)
                .centerCrop()
                .dontAnimate()
                .placeholder(R.drawable.icon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(persionImg);
        String niche = PreferenceUtil.getString("nickName", "");
        if (!TextUtils.isEmpty(niche)) {
            persionNichen.setText(niche);
        }
        String ssx = PreferenceUtil.getString("sex", "");
        if (ssx.equals("0")) {
            persionSex.setText("男");
        } else {
            persionSex.setText("女");
        }
        persionPhone.setText(PreferenceUtil.getString("telephone", ""));
    }

    @OnClick({R.id.person_img_realte, R.id.person_nichen_realte, R.id.person_sex_realte, R.id.person_phone_realte, R.id.peron_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.person_img_realte:
                check();
                break;
            case R.id.person_nichen_realte:
                setNickname();
                break;
            case R.id.person_sex_realte:
                showSexChooseDialog();
                break;
            case R.id.person_phone_realte:
//                ToastUtils.ShortToast("点我电话干嘛");
                break;
            case R.id.peron_button:
                updata();
                break;
        }
    }
    private void check() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(PersonActivity.this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA
        }, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                go();
            }


            @Override
            public void onDenied(String permission) {
                ToastUtils.ShortToast("用户拒绝授权");
            }
        });
    }

    private void go() {
        Intent intent = new Intent(PersonActivity.this, PhotoPickerActivity.class);
        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);
        startActivityForResult(intent, 1);
    }

    private void setNickname() {
        AlertDialog.Builder builder = new AlertDialog.Builder(PersonActivity.this);
        final ClearEditText nickname_input;
        final AlertDialog dialog;
        View dialgview = LayoutInflater.from(PersonActivity.this).inflate(R.layout.person_nickname_dilog_layout, null, false);
        dialog = builder.setView(dialgview).create();
        if (dialog.isShowing()) {
            dialog.dismiss();
        } else {
            dialog.show();
        }
        nickname_input = (ClearEditText) dialgview.findViewById(R.id.dilog_nickname_reset_input);
        nickname_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().length() == 8) {
                    ToastUtils.ShortToast("昵称长度最多8个字");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        dialgview.findViewById(R.id.dilog_nickname_reset_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialgview.findViewById(R.id.dilog_nickname_reset_comfrim).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nichen = nickname_input.getText().toString().trim();
                persionNichen.setText(nichen);
                dialog.dismiss();
            }
        });
    }

    /* 性别选择框 */
    private void showSexChooseDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);// 自定义对话框
        builder.setSingleChoiceItems(sexArry, 0, new DialogInterface.OnClickListener() {// 2默认的选中

            @Override
            public void onClick(DialogInterface dialog, int which) {// which是被选中的位置
                // showToast(which+"");
                persionSex.setText(sexArry[which]);
                if (sexArry[which].equals("男")) {
                    sex = 0;
                } else {
                    sex = 1;
                }
                dialog.dismiss();// 随便点击一个item消失对话框，不用点击确认取消
            }
        });
        builder.show();// 让弹出框显示
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                upimg(result);
            }
        }
    }

    private void upimg(ArrayList<String> list) {
        String first = "";
        final Map<String, Object> paramsMap = new HashMap<>();
        //上传空间
        paramsMap.put(Params.BUCKET, BaseApi.SPACE);
        //保存路径，任选其中一个
        //        dyReleaseEntityList
        String date = TimeUtil.parseDate(new Date().getTime());
        if (list.size() != 0) {
            first = list.get(0);
        }
        File file = null;
        String filepath = first;
        String geshi = filepath.substring(filepath.lastIndexOf("."));
        String savePath = "/uploads/" + date + "/" + UUID.randomUUID().toString().replaceAll("-", "") + geshi;
        file = new File(filepath);
        //表单上传（本地签名方式）
        paramsMap.put(Params.SAVE_KEY, savePath);
        UploadEngine.getInstance().formUpload(file, paramsMap, BaseApi.OPERATER, UpYunUtils.md5(PASSWORD), completeListener, progressListener);
    }

    //结束回调，不可为空
    UpCompleteListener completeListener = new UpCompleteListener() {
        @Override
        public void onComplete(boolean isSuccess, String result) {
            Log.e(TAG, isSuccess + ":" + result);
            if (isSuccess == true) {
//                mResults.add(paths.get(i));
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    userimgurl = jsonObject.getString("url");
                    ToastUtils.ShortToast("上传图片成功！");
                    Glide.with(PersonActivity.this)
                            .load(BaseApi.BASEUR_IMG + userimgurl)
                            .centerCrop()
                            .dontAnimate()
                            .placeholder(R.drawable.icon)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(persionImg);
                    LogUtils.e("lidaming", "userimgurl=" + userimgurl);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                ToastUtils.ShortToast("上传图片失败！");
            }
        }
    };
    //进度回调，可为空
    UpProgressListener progressListener = new UpProgressListener() {
        @Override
        public void onRequestProgress(final long bytesWrite, final long contentLength) {
//            uploadProgress.setProgress((int) ((100 * bytesWrite) / contentLength));
//            textView.setText((100 * bytesWrite) / contentLength + "%");
            Log.e(TAG, (100 * bytesWrite) / contentLength + "%");
            Log.e(TAG, bytesWrite + "::" + contentLength);
        }
    };

    private void updata() {
        //userimgurl头像地址 性别sex 昵称nichen
        String user_id = PreferenceUtil.getString("id", "");
        String phone = PreferenceUtil.getString("telephone", "");
        String token = PreferenceUtil.getString("token", "");
        if (TextUtils.isEmpty(userimgurl)) {
            userimgurl = PreferenceUtil.getString("headImg", "");
        } else {
            userimgurl = BaseApi.BASEUR_IMG + userimgurl;
        }
        if (persionSex.getText().toString().equals("男")) {
            sex = 0;
        } else {
            sex = 1;
        }
        OkHttpUtils.post()
                .url(BaseApi.UPDATAUSER)
                .addParams("id", user_id)
                .addParams("telephone", phone)
                .addParams("token", token)
                .addParams("headimg", userimgurl)
                .addParams("sex", sex + "")
                .addParams("nickname", persionNichen.getText().toString())
                .build().execute(new OkManagerCallback(this) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.e(TAG, "response=" + response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        String userid = jsonObject1.getString("id");
                        String telephone = jsonObject1.getString("telephone");
                        String headImg = jsonObject1.getString("headimg");
                        int sex = jsonObject1.getInt("sex");
                        String nickName = jsonObject1.getString("nickname");
                        PreferenceUtil.put("id", userid);
                        PreferenceUtil.put("telephone", telephone);
                        PreferenceUtil.put("headImg", headImg);
                        PreferenceUtil.put("sex", sex + "");
                        PreferenceUtil.put("nickName", nickName);
                        ToastUtils.ShortToast("保存成功");
                        EventBus.getDefault().post(new SenEvent("2"));
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

}
